#!/bin/sh

do_chown()
{
  if is-tv-box || is-storage-box; then
    chown $1 $2
  fi
}

get_if_nonblank()
{
  nvram=$1
  filename=$2
  perm=$3
  v=$(hnvram -qr "$nvram")
  [ -n "$v" ] && \
    echo "$v" >"$filename" && \
    do_chown root.video "$filename" && \
    chmod $perm "$filename"
}

mkdir_video()
{
  dirname=$1
  perm=$2
  mkdir -p "$dirname" && \
    do_chown root.video "$dirname" && \
    chmod $perm "$dirname" || \
    exit 1
}

case "$1" in
  start)
    mkdir_video /tmp/ssl 0555
    mkdir_video /tmp/ssl/certs 0555
    mkdir_video /tmp/ssl/private 0550
    get_if_nonblank GOOGLE_SSL_CRT /tmp/ssl/certs/device.pem 0444
    get_if_nonblank GOOGLE_SSL_PEM /tmp/ssl/private/device.key 0440
    if [ -f /tmp/ssl/certs/device.pem ]; then
      cat /tmp/ssl/certs/device.pem | logos certlog
    fi
    ;;
  stop)
    ;;
  restart)
    $0 stop; $0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
    ;;
esac
